A take home reference for writing exam and assignment solutions in R Markdown. All exam submissions in this course should be a knitted .pdf or .html generated from an .Rmd source.
Instructor: K.M. Tanvir • Institute of Statistical Research and Training (ISRT), University of Dhaka
R Markdown is a plain text file (.Rmd) that mixes three things: normal prose written in Markdown, R code inside "chunks" that runs when you knit the file, and math or tables. When you press Knit in RStudio, the file compiles into a polished PDF, HTML, or Word document with your code, its output, and your interpretation all in one place.
You write prose, followed by a code chunk. When knitted, the reader sees:
Everything you need ships with RStudio. Only a small install step is needed the first time.
# In the R console, once per machine
install.packages(c("rmarkdown", "knitr"))
# For PDF output, you also need a LaTeX distribution.
# The lightweight option that just works everywhere:
install.packages("tinytex")
tinytex::install_tinytex() # run once, takes 5-10 minutes
.Rmd into the editor. Save it with a descriptive name like ast232_final_2026.Rmd.
Every R Markdown document has three parts, always in this order.
---
title: "AST 232 Final Exam Solutions"
author: "Your Name, Roll 12345"
date: "2026-08-10"
output: pdf_document
---
# Introduction
Prose goes here. Write in **bold** and *italic*
just like in normal Markdown.
## Question 1
The next block is an R code chunk. Everything between the triple
backticks runs when we knit.
```{r q1-anova}
data(iris)
model <- aov(Sepal.Length ~ Species, data = iris)
summary(model)
```
Interpretation of the ANOVA goes here, again in prose.
--- lines) tells knitr what to build and how.```{r} and ```. Give each chunk a short name (like q1-anova) to help debugging.Only three fields matter for exam submissions: title, author, and output.
---
title: "AST 232 Final Exam Solutions"
author: "K.M. Tanvir, Roll 20221234"
date: "2026-08-10"
output: pdf_document
---
Any of pdf_document, html_document, or word_document works. If knitting fails on your machine for any reason, submit the raw .Rmd file itself; it will still be graded.
output:
pdf_document:
toc: true
number_sections: true
The body is plain Markdown. Everything below works in every knitted output.
| You type | You get |
|---|---|
# Heading 1 | Largest heading |
## Heading 2 | Section heading (use for each question) |
### Heading 3 | Sub section (part (a), (b), (c)) |
**bold** | bold |
*italic* | italic |
`code` | code |
[link text](url) | hyperlink |
- item or * item | bullet list |
1. item | numbered list |
> quote | blockquote |
| empty line | new paragraph |
A chunk starts with ```{r} and ends with ```, each on its own line. Everything between runs as R code.
```{r q1-solution}
# Compute the sex ratio
M <- 157500
F <- 162500
SR <- M / F * 100
round(SR, 2)
```
When knitted, the reader sees the code (in a grey box), then the output [1] 96.92. If a chunk produces a plot, the plot appears inline.
Options go inside the curly braces after r, comma separated: ```{r my-chunk, echo=FALSE, message=FALSE}. The most useful ones:
| Option | Effect | Common use |
|---|---|---|
echo | Show the code in the output | echo = FALSE hides code but keeps the result |
eval | Actually run the code | eval = FALSE shows code without running it |
include | Show anything at all | include = FALSE runs silently, hides both code and output. Great for setup chunks. |
message | Print R's messages | message = FALSE to hide "Attaching package" chatter |
warning | Print R's warnings | warning = FALSE for cleaner output |
results | How to render results | results = 'hide' to run silently, 'asis' for raw HTML/LaTeX output |
fig.width, fig.height | Plot size in inches | fig.width = 6, fig.height = 4 for a compact chart |
fig.cap | Figure caption | fig.cap = "Rice yield by fertilizer" |
fig.align | Alignment | fig.align = 'center' |
Set once at the top of the document with a setup chunk, then every later chunk inherits the defaults.
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE, # show code by default
message = FALSE, # hide package chatter
warning = FALSE, # hide warnings from the reader
fig.width = 6,
fig.height = 4,
fig.align = "center"
)
```
Sometimes you want a single R value in the middle of a sentence. Wrap it in `r ... ` (backtick, r, space, code, backtick).
The mean rice yield was `r `round(mean(rice$yield), 2)` Mg/ha,
with a sample standard deviation of `r `round(sd(rice$yield), 2)`.
When knitted this reads as: "The mean rice yield was 4.78 Mg/ha, with a sample standard deviation of 0.66." No manual copy paste.
Plain R output like an ANOVA table prints as monospaced text, which reads fine but is not publication grade. knitr::kable() renders any data frame as a formatted table.
```{r anova-table}
model <- aov(yield ~ treat, data = rice)
knitr::kable(
summary(model)[[1]],
digits = 3,
caption = "ANOVA table for the rice fertilizer trial"
)
```
digits controls rounding, caption adds a numbered caption, col.names renames the columns, align = 'lrrr' sets alignment column by column (l, c, r).
Every base R plot inside a chunk lands in the knitted output automatically. No ggsave or file handling needed.
```{r yield-boxplot, fig.width=6, fig.height=4, fig.cap="Yield by fertilizer"}
boxplot(yield ~ treat, data = rice,
col = "#dbeafe", border = "#2563eb",
xlab = "Fertilizer", ylab = "Yield (Mg/ha)")
```
Two things to remember:
yield-boxplot) becomes the filename of the generated figure.fig.width and fig.height per chunk for anything unusual. Default globals cover 95% of cases.Math uses LaTeX syntax and renders beautifully in every output format. Two flavours:
$\bar{y} = \frac{1}{n}\sum_{i=1}^n y_i$ renders as an inline equation.The Fergany method computes the probability of dying as
$$
_nq_x = 1 - e^{-n \cdot {_nM_x}}
$$
so the survivors column follows from $l_{x+n} = l_x \cdot _np_x$
with $_np_x = 1 - {_nq_x}$.
\alpha, \beta, \tau, \sigma, \mu. Fractions: \frac{a}{b}. Sums: \sum_{i=1}^n x_i. Subscripts: x_i. Superscripts: x^2. Bold vector: \mathbf{x}. Hat: \hat{y}.
Once the file is written, press the Knit button in RStudio (or Ctrl/Cmd + Shift + K). RStudio runs every chunk in order, then compiles the output.
| output: field | Produces | Notes |
|---|---|---|
pdf_document | PDF via LaTeX | Requires tinytex. The standard for exam submissions. |
html_document | Self contained HTML page | Best for lab work and quick previews. |
word_document | Editable .docx | Useful when a supervisor needs to add comments in Word. |
Copy this into a new .Rmd file to start your exam. Change the header, replace the placeholders, and knit.
---
title: "AST 232 Final Exam Solutions"
author: "Your Name, Roll 20221234"
date: "`r format(Sys.Date())`"
output:
pdf_document:
toc: true
number_sections: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE,
fig.width = 6, fig.height = 4, fig.align = "center"
)
```
# Question 1: Fertility measures for a district
## (a) Compute the Total Fertility Rate
```{r q1a}
age_group <- c("15-19", "20-24", "25-29", "30-34",
"35-39", "40-44", "45-49")
female_pop <- c(110000, 105000, 100000, 95000,
85000, 75000, 65000)
births <- c(8000, 15000, 11000, 7000,
2200, 600, 100)
ASFR <- births / female_pop * 1000
TFR <- 5 * sum(ASFR) / 1000
round(TFR, 3)
```
The Total Fertility Rate is `r `round(TFR, 2)` children per woman,
slightly above the replacement level of 2.10.
## (b) Interpretation
Write your interpretation here in normal prose.
# Question 2: Randomized Complete Block Design
## (a) Fit the ANOVA
```{r q2a}
# Type the data, fit the model, print the ANOVA
```
## (b) Tukey HSD
```{r q2b}
# TukeyHSD on the treatment factor
```
You referred to a variable that was never defined in the file. Something you typed in the console works there but the knit session cannot see it. Put the definition in a chunk.
If TinyTeX is installed but the build fails, the missing LaTeX package usually installs itself the next time you knit. If the same error repeats, run tinytex::reinstall_tinytex() once.
Set fig.width and fig.height on the offending chunk. For a full page landscape figure try fig.width = 8, fig.height = 5.
Add message = FALSE and warning = FALSE to your global setup chunk (see Section 7).
Save the file as UTF 8 (File → Save with Encoding → UTF 8). For PDF, ensure the LaTeX engine supports the character set; for Bangla text prefer xelatex in the YAML: output: pdf_document: latex_engine: xelatex.
Close and reopen the .Rmd file. If the problem persists, save your work, restart RStudio, and try again.